import React, { useState, useEffect } from 'react'
import styles from '../../style/childPublic/childPublic.module.less'
import pesticideStatisticsStyle from '../../style/pesticideStatistics/pesticideStatistics.module.less'
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import { DownOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons';
import { Dropdown, Space, Input, DatePicker, Button, Pagination, message, Empty } from 'antd';
import { getOutIntoGoodsList, getGoodsJoin } from '../../apis/pesticideStatistics'
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

export default function PesticideStatistics() {
    dayjs.locale('zh-cn');
    const [messageApi, contextHolder] = message.useMessage();
    const key = 'updatable';
    const [keyValue, setKeyValue] = useState('');
    const { RangePicker } = DatePicker;
    const [pesticideStatisticsList] = useState([
        { id: 1, title: '入库' },
        { id: 0, title: '出库' },
    ])
    const [contentList, setContentList] = useState([])
    const [showId, setShowId] = useState(1)
    const [title] = useState('农药统计查询监管平台');
    const [areaList, setAreaList] = useState({
        type: 1,
        type_id: "",//农药类型
        start_time: "",
        end_time: "",
        clientOrOffer: "",
        keywords: '',   //商品名或者登记证号
        listSize: '',
        pageNum: 1,
        pageSize: 10,
        area_id: localStorage.getItem('areaId'),
        area_level: localStorage.getItem('areaLevel'),
        user_name: '', //经营者名称
        zhen: '',  //镇的id,
        typeName: '请选择农药种类',
        zhenName: '请选择区域'
    })
    const [typeID, setTypeId] = useState({
        type: 1,
        pageNum: 1,
        pageSize: 10,
    })
    const [count, setCount] = useState(0)
    const [allWeight, setAllWeight] = useState(0)
    const pesticideStatisticsClick = (id) => {
        setShowId(id)
        setAreaList({ ...areaList, type: id })
        setTypeId({ ...typeID, type: id })
    }
    const [itemsType, setItemsType] = useState([])
    const [itemsArea, setItemsArea] = useState([])

    useEffect(() => {

        getGoodsJoins()
        getStatistics()
    }, [typeID]);
    // 获取列表数据
    const getStatistics = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getOutIntoGoodsList(areaList)
        if (data.state === 1) {
            setContentList(data.number);
            setCount(data.count);
            setAllWeight(data.zong_number)
            messageApi.destroy()
            if (data.count !== 0) {
                messageApi.open({
                    key,
                    type: 'success',
                    content: '数据加载完成!',
                    duration: 2,
                });
            } else {
                messageApi.warning({
                    content: '暂无数据!',
                })
            }
        } else {
            messageApi.open({
                type: 'error',
                content: data.msg,
            });
        }
    };
    // 查询
    const getStatisticsSearch = () => {
        setTypeId({
            ...typeID,
            pageNum: 1
        })
        setAreaList({
            ...areaList,
            pageNum: 1
        })
    }


    // 切换页码
    const onChangePage = (page, pageSize) => {
        setTypeId({
            ...typeID,
            pageNum: page
        })
        setAreaList({
            ...areaList,
            pageNum: page
        })
    };
    // 分页
    const itemRender = (_, type, originalElement) => {

        if (type === 'prev') {
            return <a>上一页</a>;
        }
        if (type === 'next') {
            return <a>下一页</a>;
        }
        return originalElement;
    };
    // 农药类型下拉列表
    const getGoodsJoins = async () => {
        const { data } = await getGoodsJoin()
        if (data.state === 1) {
            const newType = data.typeList.map((item, i) => {
                return { key: item.id, label: item.name }
            })
            const newArea = data.areaList.map((item, i) => {
                return { key: item.id, label: item.name }
            })
            setItemsType(newType)
            setItemsArea(newArea)
        }
    };
    // 选择的农药类型
    const getType = ({ key }) => {

        const item = itemsType.filter(item => item.key == key)[0]
        message.info(`选择了${item.label}`);
        setAreaList({ ...areaList, type_id: key, typeName: item.label })
    };
    // 下拉区域选择的内容
    const getItem = ({ key }) => {

        const item = itemsArea.filter(item => item.key == key)[0]
        message.info(`选择了${item.label}`);
        setAreaList({ ...areaList, zhen: key, zhenName: item.label })
    }
    // 双向绑定输入框
    const handleInputChange = (e) => {
        const { name, value } = e.target
        switch (name) {
            case 'user_name':
                setAreaList({ ...areaList, user_name: value })
                break;
            case 'keywords':
                setAreaList({ ...areaList, keywords: value })
                break;
            default:
                setAreaList({ ...areaList, clientOrOffer: value })
                break;
        }
    };
    // 重置数据
    const resetTo = () => {
        for (let prop in areaList) {
            if (prop !== 'area_id' && prop !== 'area_level' && prop !== 'type')
                setAreaList(areaList[prop] = '')
        }
        setKeyValue(new Date());
        setAreaList({ ...areaList, zhenName: '请选择区域', typeName: '请选择农药种类', pageNum: 1, pageSize: 10 })
        setTypeId({ ...typeID, pageNum: 1 })

    }
    // 时间选择
    const onChangeDate = (date, dateString) => {

        setAreaList({ ...areaList, start_time: dateString[0], end_time: dateString[1] })
    };


    return (
        <div className={styles.pubBack}>
            {contextHolder}
            <HeaderTop title={title}></HeaderTop>
            <div className={pesticideStatisticsStyle.contentBack}>
                <div className={pesticideStatisticsStyle.topBox}>
                    {
                        pesticideStatisticsList.map(item => {
                            return (
                                <div className={showId === item.id ? `${pesticideStatisticsStyle.topTitle} ${pesticideStatisticsStyle.show}` : `${pesticideStatisticsStyle.topTitle}`} key={item.id} onClick={() => pesticideStatisticsClick(item.id)}>
                                    {item.title}
                                </div>
                            )
                        })
                    }
                </div>
                {/* 共计总量 */}
                <div className={pesticideStatisticsStyle.entity}>
                    <span>共计总量</span>
                    <span>{allWeight}
                        <i>kg</i>
                    </span>
                </div>

                {/* 筛选 */}
                <div className={pesticideStatisticsStyle.selection}>
                    <ul>
                        <li>
                            <span>区域与经营者</span>
                            <div className={pesticideStatisticsStyle.listStyle}>
                                <Dropdown
                                    menu={{
                                        items: itemsArea,
                                        onClick: getItem

                                    }}
                                    trigger={['click']}

                                >
                                    <Space>
                                        {areaList.zhenName}
                                        <DownOutlined />
                                    </Space>
                                </Dropdown>
                                <Input name='user_name' value={areaList.user_name} onChange={handleInputChange} placeholder="请输入经营者名称" />
                            </div>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <span>商品查询</span>
                            <div className={pesticideStatisticsStyle.listStyle}>
                                <Dropdown
                                    menu={{
                                        items: itemsType,

                                        onClick: getType,

                                        selectable: true,
                                    }}

                                    trigger={['click']}
                                    // open={open}
                                    placement="bottom"
                                >
                                    {/* <a onClick={(e) => e.preventDefault()}></a> */}


                                    <Space>
                                        {areaList.typeName}
                                        <DownOutlined />
                                    </Space>

                                </Dropdown>
                                <Input name='keywords' value={areaList.keywords}
                                    onChange={handleInputChange}
                                    placeholder="请输入商品名称/登记证号" />
                            </div>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <span>时间查询</span>
                            <div>
                                <Space direction="vertical" size={12} locale={locale}>
                                    <RangePicker
                                        defaultValue={dayjs('2015-01-01', 'YYYY-MM-DD')}
                                        placeholder={['开始时间', '结束时间']}
                                        onChange={onChangeDate}
                                        key={keyValue}

                                        style={{
                                            color: 'white',
                                            backgroundColor: '#0D2147',
                                            outline: 'none',
                                            border: 'none'

                                        }}

                                    />
                                </Space>
                            </div>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <span>购买该商品客户</span>
                            <div>
                                <Input name='clientOrOffer' value={areaList.clientOrOffer} onChange={handleInputChange} placeholder="请输入客户名称" />
                            </div>
                        </li>
                    </ul>
                    <ul>
                        <li>
                            <Button type="primary" icon={<SearchOutlined />} onClick={() => getStatisticsSearch()}>
                                查询
                            </Button>
                            <Button type="primary" icon={<SyncOutlined />} onClick={() => resetTo()}>

                                重置
                            </Button>
                        </li>
                    </ul>


                </div>
                {/* 列表 */}
                <div className={pesticideStatisticsStyle.listBox}>
                    <table>
                        <thead>
                            <th>商品</th>
                            <th>{showId === 1 ? '入库数量' : '出库数量'}</th>
                            <th>种类</th>
                            <th>规格</th>
                            <th>总价</th>
                        </thead>
                        <tbody className={contentList.length !== 0 ? "" : `${pesticideStatisticsStyle.noShowData}`}>
                            {
                                contentList.map(item => {
                                    return (
                                        <tr key={item.goods_id}>
                                            <td>{item.goods_name}</td>
                                            {
                                                showId === 1 ?
                                                    <td>{item.into_number === undefined ? '查询中' : item.into_number + item.pack_name}</td> :
                                                    <td>{item.out_number === undefined ? '查询中' : item.out_number + item.pack_name}</td>
                                            }

                                            <td>{item.type_name}</td>
                                            <td>{item.specification_nuber}{item.unit_name}/{item.pack_name}</td>
                                            <td>{item.total_prices}</td>

                                        </tr>
                                    )
                                })
                            }
                        </tbody>
                        <tr className={contentList.length === 0 ? `${pesticideStatisticsStyle.emptyData}` : `${pesticideStatisticsStyle.noShowData}`}>
                            <td colSpan={7} style={{ textAlign: 'center' }}>
                                <Empty
                                    image="http://120.79.70.96:10301/mapimg/kong_he.png"
                                    imageStyle={{
                                        height: 150,
                                    }} />


                            </td>
                        </tr>
                    </table>
                </div>
                {/* 页尾 */}
                <div className={pesticideStatisticsStyle.pagActive}>
                    <Pagination total={count} current={areaList.pageNum} defaultCurrent={1} showTotal={(count) => `共 ${count} 条记录`} itemRender={itemRender} pageSize={10} onChange={onChangePage} showSizeChanger={false} />
                </div>

            </div>
        </div>
    )
}
